package com.hk.springtrains.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

@Service
public class MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;


    public void  sendMail(){
        System.out.println(new Date());
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("dujiang516@126.com");
        mailMessage.setTo("dujiang@hkjtgc.com");
        mailMessage.setSubject("Test");
        //mailMessage.setText("This is from Spring Mail");
        mailSender.send(mailMessage);
        System.out.println(new Date());
    }


    /**
     * 发送带有附件的邮件
     */
    public void senMailWithAttachment() throws MessagingException, IOException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom("dujiang516@126.com");
        helper.setTo("dujiang@hkjtgc.com");
        helper.setSubject("Test");
        System.out.println(new ClassPathResource("/123.png").getFile().exists());
        helper.addAttachment("123.png",new ClassPathResource("/123.png"));
        mailSender.send(message);
    }



}
